package com.youease.chris.control
{
	import com.youease.chris.manager.GlobalObject;
	import com.youease.chris.manager.ImageLoader;
	import com.youease.chris.model.proxy.LayerDataProxy;
	import com.youease.chris.model.proxy.MapDataProxy;
	import com.youease.chris.model.vo.IndexBitmap;
	import com.youease.chris.model.vo.LayerData;
	import com.youease.chris.utils.*;
	import com.youease.chris.view.mediator.MapSceneMediator;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.utils.Dictionary;
	
	import mx.core.UIComponent;
	
	import org.puremvc.as3.interfaces.ICommand;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;
	
	public class MapSceneCommand extends SimpleCommand implements ICommand
	{
		public static const CREATE_SCENE:String = "create_scene";
		public static const CREATE_SCENE_TYPE_ADDLAYER:String = "create_scene_addLayer"
		public static const CREATE_SCENE_TYPE_DELLAYER:String = "create_scene_delLayer"
		public static const CREATE_SCENE_COMPLETE:String = "create_scene_complete";
		public static const CREATE_SCENE_LAYER_CHANGED:String = "create_scene_layer_changed";
		
		private var mapDataProxy:MapDataProxy;
		private var mapSceneMediator:MapSceneMediator;
		private var alphaBitmapData:BitmapData = null;//new BitmapData(1,1,true,0x00FF0000);
		
		private const gridStroke:int = 1;
		private const gridColor:int = 0x0;
		private const gridAlpha:Number = .5;
		
		private var mapRows:int;
		private var mapCols:int;
		private var tileWidth:Number;
		private var tileHeight:Number;
		
		[Embed(source="assets/land0.gif")]
		private var Tile01:Class;
		
		[Embed(source="assets/hill0.gif")]
		private var Tile02:Class;
		
		[Embed(source="assets/cross.gif")]
		private var crossBg:Class;
		
		public function MapSceneCommand()
		{
			super();
		}
		
		override public function execute(notification:INotification):void {
			if(this.facade.hasProxy(GlobalObject.currentMap)) {
				mapDataProxy = this.facade.retrieveProxy(GlobalObject.currentMap) as MapDataProxy;
				mapSceneMediator = this.facade.retrieveMediator(MapSceneMediator.NAME) as MapSceneMediator;
				mapRows = mapDataProxy.mapData.mapRows;
				mapCols = mapDataProxy.mapData.mapCols;
				tileWidth = mapDataProxy.mapData.tileWidth;
				tileHeight = mapDataProxy.mapData.tileHeight;
				GlobalObject.cellWidth = tileWidth;
				GlobalObject.cellHeight = tileHeight;
			}
			switch(notification.getType()) {
				case CREATE_SCENE_TYPE_ADDLAYER:
					var addedLayer:LayerData = new LayerData(mapDataProxy.mapData.name+"_"+"layer"+mapDataProxy.mapData.layers.length,mapDataProxy.mapData);
					GlobalObject.currentLayer = addedLayer.name;
					var addedLayerProxy:LayerDataProxy = new LayerDataProxy(addedLayer);
					mapDataProxy.addLayer(addedLayer);
					this.facade.registerProxy(addedLayerProxy);
					addLayer(addedLayer,false);
					break;
				case CREATE_SCENE_TYPE_DELLAYER:
					mapDataProxy.deleteLayer(notification.getBody() as LayerData);
					deleteLayer((notification.getBody() as LayerData).name);
					break;
				default:
					mapDataProxy = notification.getBody() as MapDataProxy;
					GlobalObject.currentMap = mapDataProxy.mapData.name;
					mapSceneMediator = this.facade.retrieveMediator(MapSceneMediator.NAME) as MapSceneMediator;
					mapSceneMediator.layerBitmaps = new Dictionary();
					mapSceneMediator.layerUI = new Dictionary();
					mapSceneMediator.mapContainer.removeAllChildren();
					//			drawISOLayers();
					//			drawISOGrid();
					mapRows = mapDataProxy.mapData.mapRows;
					mapCols = mapDataProxy.mapData.mapCols;
					
				GlobalObject.centerGridX = GlobalObject.centerGridY = int(mapCols/2);
				
					tileWidth = mapDataProxy.mapData.tileWidth;
					tileHeight = mapDataProxy.mapData.tileHeight;
					drawLayers();
					drawGrid();
//					drawCrossLayer();
					
					sendNotification(CREATE_SCENE_COMPLETE,mapDataProxy);
			}
		}
		/**
		 * 从0，0开始斜着往上放置	,如果用幻三的图斜上方的图会压住下面的，但这种方式最方便
		 */ 
		private function drawLayersSideling ():void {
			var bitmapData:BitmapData = (new Tile01() as Bitmap).bitmapData;
			for each(var layer:LayerData in mapDataProxy.mapData.layers) {
				trace(layer.name);
				mapSceneMediator.layerBitmaps[layer.name] = new Vector.<Bitmap>();
				mapSceneMediator.layerUI[layer.name] = new UIComponent();
				for(var i:int=0;i<mapDataProxy.mapData.mapRows;i++) {
					for(var j:int=0;j<mapDataProxy.mapData.mapCols;j++) {
						var bitmap:Bitmap = new Bitmap();
						//bitmap.bitmapData = bitmapData;
						mapSceneMediator.layerUI[layer.name].addChild(bitmap);
						
						bitmap.x = -mapDataProxy.mapData.mapCols*mapDataProxy.mapData.tileWidth/2 + j*mapDataProxy.mapData.tileWidth/2 + i*mapDataProxy.mapData.tileWidth/2;
						bitmap.y = -j*mapDataProxy.mapData.tileHeight/2 + i*mapDataProxy.mapData.tileHeight/2 - 75;
						
						mapSceneMediator.layerBitmaps[layer.name].push(bitmap);
						
					}
				}
				mapSceneMediator.mapContainer.addChild(mapSceneMediator.layerUI[layer.name]);
			}
		}
		/**
		 * 从顶部开始（gridWidth/2,-gridheight/2）横着金字塔型放置，1,2,3,4...和幻三的放置方式一样
		 */
		private function drawLayers():void {
			for each(var layer:LayerData in mapDataProxy.mapData.layers) {
				addLayer(layer,true);
				continue;
			}
		}
		
		private function drawGrid():void {
			
			var dragLayer:MyUicomponent = new MyUicomponent("dragLayer");
			var uicomp:MyUicomponent = new MyUicomponent("grid");
			mapSceneMediator.layerUI["grid"] = uicomp;
			var grid:Sprite = new Sprite();
			
			//画行
			for(var i:int=0;i<=mapDataProxy.mapData.mapRows;i++) {
				grid.graphics.lineStyle(gridStroke,gridColor,gridAlpha);
				grid.graphics.moveTo(i*mapDataProxy.mapData.tileWidth/2,i*mapDataProxy.mapData.tileHeight/2);
				grid.graphics.lineTo(i*mapDataProxy.mapData.tileWidth/2+mapDataProxy.mapData.mapCols*mapDataProxy.mapData.tileWidth/2,
										i*mapDataProxy.mapData.tileHeight/2-mapDataProxy.mapData.mapCols*mapDataProxy.mapData.tileHeight/2);
			}
			//画列
			for(var j:int=0;j<=mapDataProxy.mapData.mapCols;j++) {
				grid.graphics.lineStyle(gridStroke,gridColor,gridAlpha);
				grid.graphics.moveTo(j*mapDataProxy.mapData.tileWidth/2,-j*mapDataProxy.mapData.tileHeight/2);
				grid.graphics.lineTo(j*mapDataProxy.mapData.tileWidth/2+mapDataProxy.mapData.mapRows*mapDataProxy.mapData.tileWidth/2,
										-j*mapDataProxy.mapData.tileHeight/2+mapDataProxy.mapData.mapRows*mapDataProxy.mapData.tileHeight/2);
			}
			grid.cacheAsBitmap = true;
			uicomp.addChild(grid);
			grid.x = -mapDataProxy.mapData.mapCols*mapDataProxy.mapData.tileWidth/2;
			
			trace(mapSceneMediator.mapScene.width+"...xx...."+mapSceneMediator.mapScene.height);
			dragLayer.graphics.beginFill(0,.001);
			dragLayer.graphics.drawRect(-(grid.width-gridStroke)/2,-(grid.height-gridStroke)/2,grid.width-gridStroke,grid.height-gridStroke);
			dragLayer.graphics.endFill();
			
			mapSceneMediator.mapContainer.addChild(uicomp);
			mapSceneMediator.mapContainer.addChildAt(dragLayer,0);
			
			mapSceneMediator.mapContainer.x = mapSceneMediator.mapScene.width/2;
			mapSceneMediator.mapContainer.y = mapSceneMediator.mapScene.height/2;
			
		}
		/**
		 * 绘制不可通过层
		*/
		private function drawCrossLayer():void {
			mapSceneMediator.layerBitmaps[GlobalObject.crossLayerName] = new Vector.<Bitmap>(mapRows*mapCols);
			mapSceneMediator.layerUI[GlobalObject.crossLayerName] = new MyUicomponent(GlobalObject.crossLayerName);
			mapSceneMediator.layerRender[GlobalObject.crossLayerName] = new Array();
			
			var currentGridX:int = 0;
			var currentGridY:int = mapCols - 1;
			
			var firstGridX:int = 0;
			var firstGridY:int = mapCols - 1;
			
			var flag:Boolean = true;//区分上半部分和下半部分的标志位
			
			for(var i:int=0;i<mapRows*mapCols;i++) {
				var bitmap:Bitmap = new crossBg();
				bitmap.cacheAsBitmap = true;
				bitmap.alpha = 0;
				//					bitmap.bitmapData = bitmapData;
				if(currentGridY<GlobalObject.centerGridY+GlobalObject.rendererRange && currentGridY>GlobalObject.centerGridY-GlobalObject.rendererRange && 
					currentGridX<GlobalObject.centerGridX+GlobalObject.rendererRange && currentGridX>GlobalObject.centerGridX-GlobalObject.rendererRange) {
					mapSceneMediator.layerRender[GlobalObject.crossLayerName].push(bitmap);
					mapSceneMediator.layerUI[GlobalObject.crossLayerName].addChild(bitmap);
				}
				
				//从顶部开始（gridWidth/2,-gridheight/2）横着放置，1,2,3,4...和幻三的放置一样
				bitmap.x = -mapCols*tileWidth/2 + currentGridY*tileWidth/2 + currentGridX*tileWidth/2;
				bitmap.y = -currentGridY*tileHeight/2 + currentGridX*tileHeight/2 - tileHeight*3/2;
				
				var canCross:Boolean = mapDataProxy.mapData.crossData[currentGridX +","+currentGridY];
				if(canCross) {
					bitmap.alpha = 0;
				}else {
					bitmap.alpha = .3;
				}
				
				mapSceneMediator.layerBitmaps[GlobalObject.crossLayerName][currentGridX*mapCols + currentGridY] = bitmap;
				
				if(currentGridX+1==mapRows) {
					flag = false;
				}
				
				if(flag) {
					//大菱形grid上半部分
					if(currentGridY+1==mapCols) {
						firstGridY--;
						currentGridY = firstGridY;
						currentGridX = firstGridX;
					}else {
						currentGridY++;
						currentGridX++;
					}
				}else {
					//大菱形grid下半部分
					if(currentGridX+1==mapRows) {
						firstGridX ++;
						currentGridX = firstGridX;
						currentGridY = firstGridY;
					}else {
						currentGridX++;
						currentGridY++;
					}
				}
			}
			mapSceneMediator.mapContainer.addChild(mapSceneMediator.layerUI[GlobalObject.crossLayerName]);
		}
		
		private function addLayer(layer:LayerData,first:Boolean):void {
			mapSceneMediator.layerBitmaps[layer.name] = new Vector.<IndexBitmap>(mapRows*mapCols);
			mapSceneMediator.layerRender[layer.name] = new Array();
			mapSceneMediator.layerUI[layer.name] = new MyUicomponent(layer.name);
			mapSceneMediator.layerUI[layer.name].mouseChildren = false;
			mapSceneMediator.layerUI[layer.name].mouseEnabled = false;
			
			var currentGridX:int = 0;
			var currentGridY:int = mapCols - 1;
			
			var firstGridX:int = 0;
			var firstGridY:int = mapCols - 1;
			
			var flag:Boolean = true;//区分上半部分和下半部分的标志位
			
			for(var i:int=0;i<mapRows*mapCols;i++) {
				var bitmap:IndexBitmap = new IndexBitmap(i);
				bitmap.cacheAsBitmap = true;0
				//					bitmap.bitmapData = bitmapData;
				if(currentGridY<GlobalObject.centerGridY+GlobalObject.rendererRange && currentGridY>GlobalObject.centerGridY-GlobalObject.rendererRange && 
					currentGridX<GlobalObject.centerGridX+GlobalObject.rendererRange && currentGridX>GlobalObject.centerGridX-GlobalObject.rendererRange) {
					mapSceneMediator.layerRender[layer.name].push(bitmap);
					mapSceneMediator.layerUI[layer.name].addChild(bitmap);
				}
				
				//从顶部开始（gridWidth/2,-gridheight/2）横着放置，1,2,3,4...和幻三的放置一样
				bitmap.x = -mapCols*tileWidth/2 + currentGridY*tileWidth/2 + currentGridX*tileWidth/2;// - 86;
				bitmap.y = -currentGridY*tileHeight/2 + currentGridX*tileHeight/2 - tileHeight*3/2 - 142;
				
				var tileImg:String = layer.tiles[currentGridX*mapCols + currentGridY]["textrue"]["img"];
				if(tileImg!="") {
					ImageLoader.instance.loadImg(GlobalObject.projectDir+"/textures/"+tileImg,bitmap,"bitmapData");//bitmap = TexturesManager.textures[tileImg]["bitmap"];
				}else {
					bitmap.bitmapData = alphaBitmapData;
				}
				mapSceneMediator.layerBitmaps[layer.name][currentGridX*mapCols + currentGridY] = bitmap;
				
				if(currentGridX+1==mapRows) {
					flag = false;
				}
				
				if(flag) {
					//大菱形grid上半部分
					if(currentGridY+1==mapCols) {
						firstGridY--;
						currentGridY = firstGridY;
						currentGridX = firstGridX;
					}else {
						currentGridY++;
						currentGridX++;
					}
				}else {
					//大菱形grid下半部分
					if(currentGridX+1==mapRows) {
						firstGridX ++;
						currentGridX = firstGridX;
						currentGridY = firstGridY;
					}else {
						currentGridX++;
						currentGridY++;
					}
				}
			}
			if(first) {//创建地图
				mapSceneMediator.mapContainer.addChild(mapSceneMediator.layerUI[layer.name]);
			}else {//添加层
				mapSceneMediator.mapContainer.addChildAt(mapSceneMediator.layerUI[layer.name],mapSceneMediator.mapContainer.numChildren-1);
			}
			GlobalObject.currentLayer = layer.name;
			
			this.sendNotification(CREATE_SCENE_LAYER_CHANGED);
		}
		
		private function deleteLayer(layerName:String):void {
			mapSceneMediator.mapContainer.removeChild(mapSceneMediator.layerUI[layerName]);
			delete mapSceneMediator.layerUI[layerName];
			this.sendNotification(CREATE_SCENE_LAYER_CHANGED);
		}
		
		private function drawISOLayers():void {
			var world:IsoWorld = new IsoWorld();
			trace(mapSceneMediator.mapScene.mapContainer.width/2+".......sceneWidth");
			world.x = mapSceneMediator.mapScene.mapContainer.width/2;
			world.y = 10;
			
			var uicomp:MyUicomponent = new MyUicomponent("iso");
//			uicomp.width = mapSceneMediator.mapScene.mapContainer.width;
//			uicomp.height = mapSceneMediator.mapScene.mapContainer.height;
			
			mapSceneMediator.mapScene.mapContainer.addChild(uicomp);
			
			var bitmapData:BitmapData = (new Tile01() as Bitmap).bitmapData;
			
			for(var i:int=0;i<mapDataProxy.mapData.mapRows;i++) {
				for(var j:int=0;j<mapDataProxy.mapData.mapCols;j++) {
					var tile:GraphicTile = new GraphicTile(mapDataProxy.mapData.tileWidth/2, bitmapData,mapDataProxy.mapData.tileWidth/2,mapDataProxy.mapData.tileWidth/4);
					tile.position = new Point3D(i * mapDataProxy.mapData.tileWidth/2, 0, j * mapDataProxy.mapData.tileWidth/2);
					world.addChildToFloor(tile);
				}
			}
			uicomp.addChild(world);
		}
		
		private function drawISOGrid():void {
//			for each(var layer:LayerData in mapDataProxy.mapData.layers) {
//				trace(layer.name);
//			}
			var world:IsoWorld = new IsoWorld();
			trace(mapSceneMediator.mapScene.mapContainer.width/2+".......sceneWidth");
			world.x = mapSceneMediator.mapScene.mapContainer.width/2;
			world.y = 10+mapDataProxy.mapData.tileWidth/2;
			
			var uicomp:MyUicomponent = new MyUicomponent("iso");
//			uicomp.width = mapSceneMediator.mapScene.mapContainer.width;
//			uicomp.height = mapSceneMediator.mapScene.mapContainer.height;
			
			mapSceneMediator.mapScene.mapContainer.addChild(uicomp);
			for(var i:int=0;i<mapDataProxy.mapData.mapRows;i++) {
				for(var j:int=0;j<mapDataProxy.mapData.mapCols;j++) {
					var tile:DrawnIsoTile = new DrawnIsoTile(mapDataProxy.mapData.tileWidth/2, 0xcccccc);
					tile.position = new Point3D(i * mapDataProxy.mapData.tileWidth/2, 0, j * mapDataProxy.mapData.tileWidth/2);
					world.addChildToFloor(tile);
				}
			}
			uicomp.addChild(world);
		}
	}
}